package com.moyun.zbmy.zizhou.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.util.ArrayMap;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.moyun.zbmy.zizhou.application.Cache;
import com.moyun.zbmy.zizhou.application.Constances;
import com.moyun.zbmy.zizhou.beans.ConvertRecordBean;
import com.moyun.zbmy.zizhou.beans.DoUpEvent;
import com.moyun.zbmy.zizhou.beans.FCityState;
import com.moyun.zbmy.zizhou.beans.FScribeState;
import com.moyun.zbmy.zizhou.beans.FUsers;
import com.moyun.zbmy.zizhou.beans.FocusColumn;
import com.moyun.zbmy.zizhou.beans.GovItemBean;
import com.moyun.zbmy.zizhou.beans.JiaBean;
import com.moyun.zbmy.zizhou.beans.JiaItemBean;
import com.moyun.zbmy.zizhou.beans.ShareEvent;
import com.moyun.zbmy.zizhou.http.AbsNetCallBack;
import com.moyun.zbmy.zizhou.http.ParamsEditor;
import com.moyun.zbmy.zizhou.ui.activities.LoginActivity;
import com.moyun.zbmy.zizhou.utils.UserManager;
import com.ruihang.generalibrary.ui.widget.CustomLinearLayout;
import com.ruihang.generalibrary.utils.GeneraLifeObser;
import com.ruihang.generalibrary.utils.GroupOrderHelper;
import com.ruihang.generalibrary.utils.ListUtils;
import com.moyun.zbmy.zizhou.R;
import com.moyun.zbmy.zizhou.beans.FProgram;
import com.moyun.zbmy.zizhou.http.AbsListNetCallback;
import com.moyun.zbmy.zizhou.http.NetUtils;
import com.moyun.zbmy.zizhou.ui.adapter.LookBackAdapter;
import com.moyun.zbmy.zizhou.ui.dialog.TimePopupDialog;
import com.moyun.zbmy.zizhou.utils.ListTypeUtils;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2017/7/13 0013.
 * 新闻回放页面
 */
public class ProgramBackFragment extends ColumnBaseFragment implements LookBackAdapter.ChoiceDateCallBack
        , TimePopupDialog.PopItemClick, CanRefreshLayout.OnRefreshListener
        , ExpandableListView.OnGroupClickListener, ExpandableListView.OnChildClickListener, CanRefreshLayout.IScrollView {
    @BindView(R.id.program_back_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.program_back_list)
    protected ExpandableListView proBack_list;
    @BindView(R.id.can_content_view)
    protected CustomLinearLayout scrollLay;
    private LookBackAdapter lookbackAdapter;
    private TimePopupDialog timePopupDialog;
    public static final String TIME_TAG = "dia_time_choice";
    private List<FProgram> mList;
    // private boolean mIsLoading = false;
    // private boolean isFirtShowing = true;

    private String questUrl;
    private GroupOrderHelper groupOrderHelper;
    private String programUrl;
    private String pageUrl;
    private int dateCurrentPos;
    private boolean isRequesting = false;
    private TvFragment parentFragment;
    private FProgram choosedFProgram;


    @BindView(R.id.home_tablay)
    protected SlidingTabLayout home_tablay;

    @BindView(R.id.home_tablay2)
    protected SlidingTabLayout home_tablay2;

    public static final String JIA_URL = "sctv/programType.json";
    public static final String JIA_ARRAY_URL = "getProgramNewsList";



    public ProgramBackFragment() {
    }

    public void setParentFragment(TvFragment parentFragment) {
        this.parentFragment = parentFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_program_back, container, false);
        ButterKnife.bind(this, view);
        groupOrderHelper = new GroupOrderHelper();
        return view;
    }

    @Override
    protected void initViews(View v, @Nullable Bundle savedInstanceState) {
        proBack_list.setGroupIndicator(null);
        proBack_list.setOnGroupClickListener(this);
        proBack_list.setOnChildClickListener(this);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        scrollLay.setiScrollView(this);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        getCityStateList();


    }

    @Override
    protected boolean onFragmentShow(boolean isFirst, boolean isCallFromResume) {
        if (null != parentFragment && null != choosedFProgram) {
            parentFragment.setPlayMedia(choosedFProgram);
        }
        return super.onFragmentShow(isFirst, isCallFromResume);
    }

    @Override
    public void onResume() {
        super.onResume();
        GeneraLifeObser.changeLifeState(this, GeneraLifeObser.STATE_RESUME);
    }

    @Override
    public void onDestroyView() {
        if (scrollLay != null) {
            scrollLay.setiScrollView(null);
        }
        if (proBack_list != null) {
            proBack_list.setOnChildClickListener(null);
            proBack_list.setOnGroupClickListener(null);
        }
        if (refreshLayout != null) {
            refreshLayout.setOnRefreshListener(null);
        }
        super.onDestroyView();
    }

    @Override
    public boolean canScrollUp(MotionEvent e) {
        return ViewCompat.canScrollVertically(proBack_list, -1);
    }

    @Override
    public boolean canScrollDown(MotionEvent e) {
        return ViewCompat.canScrollVertically(proBack_list, 1);
    }


    @Override
    public void getDateCallBack(int position, String url) {
        if (!TextUtils.isEmpty(url) && url.length() - 24 > 0) {
            pageUrl = url.substring(0, url.length() - 24);
            dateCurrentPos = position;
            if (timePopupDialog == null) {
                timePopupDialog = new TimePopupDialog().setPopItemClick(this);
            }
            timePopupDialog.show(getActivity().getSupportFragmentManager(), TIME_TAG);
        } else {
            toast("暂无数据");
        }
    }


    private ArrayList<String> listG = new ArrayList<String>();
    private ArrayList<String> listS = new ArrayList<String>();


    private void getCityStateList() {
        NetUtils.getNetAdapter().getJiaList(getOwnerName(), JIA_URL, new AbsNetCallBack<JiaBean>(JiaBean.class) {
            @Override
            public void onSuc(JiaBean fCityItem) {


                listG.add("全部");
                listS.add("全部");

                for(JiaItemBean item : fCityItem.getGradeList()){

                    listG.add(item.getGrade());
                }
                setData(home_tablay,listG);


                for(JiaItemBean item : fCityItem.getSubjectList()){
                    listS.add(item.getSubject());
                }
                setData(home_tablay2,listS);


                home_tablay.setOnTabSelectListener(new OnTabSelectListener() {
                    @Override
                    public void onTabSelect(int position) {
                    }

                    @Override
                    public void onTabReselect(int position) {
                        if(position ==0){
                            grade = "";
                        }else{
                            grade = listG.get(position);

                        }

                        getSecondList();
                    }

                    @Override
                    public void onTabScrollTo(int position) {

                    }
                });

                home_tablay2.setOnTabSelectListener(new OnTabSelectListener() {
                    @Override
                    public void onTabSelect(int position) {
                    }

                    @Override
                    public void onTabReselect(int position) {
                        if(position ==0){
                            subject = "";
                        }else {
                            subject = listS.get(position);
                        }

                        getSecondList();
                    }

                    @Override
                    public void onTabScrollTo(int position) {

                    }
                });


                getFirstList();

            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
            }

            @Override
            public void onEnd() {
                super.onEnd();
            }
        });
    }



    /**
     * 加载 首页中的各个栏目页面
     *
     * @param fChannels
     */
    private void setData(SlidingTabLayout home_tablay, ArrayList<String> fChannels) {

        home_tablay.setTabPadding(0);
        home_tablay.setTabSpaceEqual(true);
        home_tablay.setShowBg(true);
        home_tablay.setmTitles(fChannels);
        home_tablay.notifyDataSetChanged();

    }





    @Override
    public void getItemClick(int groupPosition, int childPosition) {
        FProgram fProgram = (FProgram) lookbackAdapter.getChild(groupPosition, childPosition);
        if (fProgram != null) {
            choosedFProgram = fProgram;
            if (null != parentFragment) {
                parentFragment.setPlayMedia(fProgram);
            }
            ArrayList<Pair<String, String>> pairs = new ArrayList<>();
            pairs.add(new Pair<>("页面", "首页"));
            pairs.add(new Pair<>("栏目", "频道"));
            pairs.add(new Pair<>("位置", "新闻回放"));
            pairs.add(new Pair<>("行为类型", "点击"));
            GridsumWebDissector.getInstance().trackEvent(ProgramBackFragment.this, "", fProgram.getProgrammeName(), "", 200, pairs);

            Cache.getInstance().setShareInfo(new ShareEvent(choosedFProgram.getSharedUrl(),choosedFProgram.getProgrammeTitle()));

        }

        //   toast("点击回看" + fProgram.getProgrammeTitle());
    }

    @Override
    public void selectTime(String year, String month, String day) {
        //toast(time);
        if (month.length() == 1) {
            month = "0" + month;
        }
        if (day.length() == 1) {
            day = "0" + day;
        }
        String dateStr = year + month + day;
        int dateInt = Integer.parseInt(dateStr);
        if (dateInt < 20180331) {
            programUrl = pageUrl + year + month + day + ".json";
        } else {
            programUrl = pageUrl + year + "/" + month + "/" + day + "/" + year + month + day + ".json";
        }

        programDate= year+ "-" + month + "-"+ day;

        //programUrl = "/sctv/lookback/2/20170715.json";
        getProList( dateCurrentPos,mList.get(dateCurrentPos).getProgrammeId());

    }

    @Override
    public void onRefresh() {
        dateCurrentPos  = 0;
        programDate = "";
        if(ListUtils.isListValued(mList)) {
            getProList(dateCurrentPos,mList.get(dateCurrentPos).getProgrammeId());
        }else{
            refreshLayout.refreshComplete();
        }

    }

    /**
     * 请求频道回看新闻数据
     */
    public void getFirstList() {
        isRequesting = true;

//        ArrayMap<String, Object> pe = new ArrayMap<>();
//        pe.put("siteNumber", Constances.SITE_ID);
//        pe.put("grade", "");
//        pe.put("subject", "");
//        pe.put("programDate", "");
//        pe.put("programbackId", "");
//        NetUtils.getNetAdapter().getJiaArray(getOwnerName(), pe
//                , new AbsNetCallBack<FProgram>(FProgram.class) {
//                    @Override
//                    public void onSuc(FProgram scribeState) {
//
//                        List<FProgram> firstList = scribeState.getProgrammeList();
//                        if (firstList == null || firstList.size() == 0 || TextUtils.isEmpty(firstList.get(0).getProgrammeUrl())) {
//                            onError(null, null);
//                            return;
//                        }
//                        mList = new ArrayList<>();
//                        mList.addAll(firstList);
//                        getSecondList();
//
//
//                    }
//
//                    @Override
//                    public void onError(Throwable ex, String errorMsg) {
//                        isRequesting = false;
//                        super.onError(ex, errorMsg);
//
//                    }
//
//                    @Override
//                    public void onEnd() {
//                        onNetFinish();
//                    }
//
//                });



        NetUtils.getNetAdapter().getProgramArray(getOwnerName(), HomeFragment.getInstance().getPlayBackUrl(), new AbsListNetCallback<FProgram>
                (ListTypeUtils.FProgram()) {

            @Override
            public void onSuc(List<FProgram> firstList) {
                if (firstList == null || firstList.size() == 0 || TextUtils.isEmpty(firstList.get(0).getProgrammeUrl())) {
                    onError(null, null);
                    return;
                }
                mList = new ArrayList<>();
                mList.addAll(firstList);
                getSecondList();
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                isRequesting = false;
                super.onError(ex, errorMsg);
            }

            @Override
            public void onEnd() {
                refreshLayout.refreshComplete();
            }
        });

    }

    private void getSecondList() {
        if(ListUtils.isListValued(mList)) {
            for (int i = 0; i < mList.size(); i++) {
                groupOrderHelper.addOne();
                String url = mList.get(i).getProgrammeUrl();
                getProList(i, mList.get(i).getProgrammeId());
            }
        }

    }

    private String  grade,subject,programDate;

    private void getProList(final int i,String programbackId) {
        isRequesting = true;
        if(!ListUtils.isListValued(mList)){
            return;
        }

        NetUtils.getNetAdapter().getJiaArray(getOwnerName(), Constances.SITE_ID, grade, subject,programDate,programbackId
                , new AbsListNetCallback<FProgram>(ListTypeUtils.ConvertRecord()) {
                    @Override
                    public void onSuc(List<FProgram> crb) {
                        initData(crb, getInt1());
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg) {
                        initData(null, getInt1());
                    }


                    @Override
                    public void onEnd() {
                        isRequesting = false;
                        refreshLayout.refreshComplete();
                    }
                }.setInt1(i));

    }




    private void initData(List<FProgram> list, int index) {
        if (ListUtils.isListValued(list)) {
            mList.get(index).setProgrammeList(list);
        } else {
            mList.get(index).setProgrammeList(null);
        }
        if (!groupOrderHelper.removeOne()) {
            return;
        }
        if (lookbackAdapter == null) {
            lookbackAdapter = new LookBackAdapter(mList, getActivity()).setChoiceDateCallBack(this);
            proBack_list.setAdapter(lookbackAdapter);
            if (mList.size() > 1) {
                proBack_list.expandGroup(0);
            }
        } else {
            lookbackAdapter.setData(mList);
//            if (mList.size() > 1) {
//                proBack_list.expandGroup(0);
//            }
        }

        initFirstData();


    }


    private void initFirstData() {
        if (ListUtils.isListValued(mList)) {
            List<FProgram> list = mList.get(0).getProgrammeList();
            proBack_list.expandGroup(0);
            if (ListUtils.isListValued(list)) {
                choosedFProgram = list.get(0);
                list.get(0).setSelect(true);
                lookbackAdapter.notifyDataSetChanged();
                getItemClick(0, 0);
            }
        }
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            //  if (!mIsLoading) {
            Fragment bf = parentFragment;
            if (parentFragment == null
                    || TextUtils.isEmpty((parentFragment).getProgramBackUrl())) {
                //toast(R.string.loading_no_data);
            } else {
            }
            //}
            //isFirtShowing = false;
        }
    }

//    public void setIsLoading(boolean isLoading) {
//        mIsLoading = isLoading;
//    }

    public void setProgramUrl(String programUrl) {
        this.programUrl = programUrl;
    }

    @Override
    public boolean onGroupClick(ExpandableListView expandableListView, View view, int groupPosition, long id) {
//        if (ListUtils.isListValued(mList.get(groupPosition).getProgrammeList())) {
//            return false;
//        }
        return false;
    }

    @Override
    public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
        for (int i = 0; i < mList.size(); i++) {
            List<FProgram> list = mList.get(i).getProgrammeList();
            if (!ListUtils.isListValued(list)) {
                continue;
            }
            for (int j = 0; j < list.size(); j++) {
                if (i == groupPosition && j == childPosition) {
                    list.get(j).setSelect(true);
                } else {
                    list.get(j).setSelect(false);
                }
            }
        }
        lookbackAdapter.notifyDataSetChanged();
        getItemClick(groupPosition, childPosition);
        return true;
    }

    public void setQuestUrl(String questUrl) {
        this.questUrl = questUrl;
    }

}
